/**
 * Created by tums on 18/8/15.
 */
import React,{Component,PropTypes} from 'react';
import {connect} from 'react-redux';
import {addTodo,addTodoAsync,completeTodo,setVisibilityFilter,VisibilityFilters} from './actions.js';
import AddTodo from './AddTodo.js';
import TodoList from './TodoList.js';
import Footer from './Footer.js';

class App extends Component {
    render() {
        const {dispatch,visibleTodos,visibilityFilter}=this.props;
        return (
            <div>
                <AddTodo onAddClick={text=>dispatch(addTodoAsync(text))}/>
                <TodoList todos={visibleTodos}
                          onTodoClick={index=>dispatch(completeTodo(index))}/>
                <Footer filter={visibilityFilter}
                        onFilterChange={filter=>dispatch(setVisibilityFilter(filter))}/>
            </div>
        );
    }
}

App.propTypes = {
    visibleTodos: PropTypes.arrayOf(PropTypes.shape({
        text: PropTypes.string.isRequired,
        completed: PropTypes.bool.isRequired
    })),
    visibilityFilter: PropTypes.oneOf([
        'SHOW_ALL',
        'SHOW_COMPLETED',
        'SHOW_ACTIVE'
    ]).isRequired
};

function selectTodos(todos, filter) {
    switch (filter) {
        case VisibilityFilters.SHOW_ALL:
            return todos;
        case VisibilityFilters.SHOW_COMPLETED:
            return todos.filter(todo=>todo.completed);
        case VisibilityFilters.SHOW_ACTIVE:
            return todos.filter(todo=>!todo.completed);
    }
}

function select(state) {
    return {
        visibleTodos: selectTodos(state.todos, state.visibilityFilter),
        visibilityFilter: state.visibilityFilter
    };
}

export default connect(select)(App);